package com.ronan.imweb.service.impl;

import com.ronan.common.constant.Constants;
import com.ronan.common.pojo.RimUmsInfo;
import com.ronan.imweb.service.RedisService;
import com.ronan.imweb.service.UmsInfoCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * FileName    : com.ronan.imweb.service.impl
 * Description :
 *
 * @author : ronan
 * @version : 1.0
 * Create Date : 2021/3/16 15:28
 **/
@Service
public class UmsInfoCacheServiceImpl implements UmsInfoCacheService {

    private static final Map<String, RimUmsInfo> RIM_USER_INFO_MAP = new ConcurrentHashMap<>();
    @Autowired
    private RedisService redisService;

    /**
     * 根据accid查询ums信息
     *
     * @param accid accid
     * @return {@link RimUmsInfo}
     */
    @Override
    public RimUmsInfo searchUmsInfoByAccid(String accid) {

        // 先从本地缓存中取
        RimUmsInfo rimUmsInfo = RIM_USER_INFO_MAP.get(accid);
        if (null != rimUmsInfo) {
            return rimUmsInfo;
        }

        // 本地没有,则从redis取
        String token = (String) redisService.get(Constants.ACCOUNT_PREFIX + accid);
        if (null != token) {
            rimUmsInfo = new RimUmsInfo(accid, token);
            // 将数据保存一份到本地缓存
            RIM_USER_INFO_MAP.put(accid,rimUmsInfo);
        }
        return rimUmsInfo;
    }

    /**
     * 在线用户
     *
     * @return {@link Set <RimUmsInfo>}
     */
    @Override
    public Set<RimUmsInfo> onlineUms() {
        Set<RimUmsInfo> ums = new HashSet<>();
        Set<Object> members = redisService.sMembers(Constants.LOGIN_STATUS_PREFIX);
        for (Object member : members) {
            RimUmsInfo rimUmsInfo = searchUmsInfoByAccid(String.valueOf(member));
            ums.add(rimUmsInfo);
        }
        return ums;
    }
}
